import { ErrorBoundary } from 'react-error-boundary' // 错误处理，避免白屏

import PageError from '@/pages/Error/404'
import { useUserInfo } from '@/store/user' // 状态获取
import { getItem } from '@/utils/storage'
import { useRouter } from '../hooks/useRouter' // 导航钩子
import { routes } from '@/router/constant'

import type { Props } from '#/index'
import type { RouteConfig } from '#/router'
import { StorageEnum } from '#/enum'
import { UserType } from '#/store'

const AuthGuard = ({ children }: Props) => {
  const router = useRouter()
  const { accessToken /* , permissions */ } = useUserInfo()
  const loaclUserInfo: UserType | null = getItem(StorageEnum.User)

  const check = useCallback(() => {
    if (!accessToken && !loaclUserInfo?.accessToken) {
      router.replace('/login')
    }
  }, [router, accessToken])

  useEffect(() => {
    check()
  }, [check])

  return <ErrorBoundary FallbackComponent={PageError}>{children}</ErrorBoundary>
}

export const loginRequest = (): Promise<RouteConfig[]> => {
  console.log('请求权限数据')
  return new Promise(res => {
    setTimeout(() => {
      res(routes)
    }, 1000)
  })
}

export default AuthGuard
